<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">


    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="书名" prop="name">
        <el-input v-model="dataForm.name" placeholder="书名" readonly></el-input>
      </el-form-item>
      <el-form-item label="版本" prop="version">
        <el-input v-model="dataForm.version" placeholder="版本" readonly></el-input>
      </el-form-item>
      <el-form-item label="出版商" prop="vendor">
        <el-input v-model="dataForm.vendor" placeholder="出版商" readonly></el-input>
      </el-form-item>
      <el-form-item label="作者" prop="vendor">
        <el-input v-model="dataForm.authorNames" placeholder="作者" readonly></el-input>
      </el-form-item>
      <el-form-item label="当前库存" prop="needBack">
        <el-input-number v-model="dataForm.needBack" disabled placeholder="图书数量"></el-input-number>
      </el-form-item>

      <el-form-item label="归还数量" prop="returnCount">
        <el-input-number v-model="dataForm.returnCount" :max="dataForm.needBack" :min="0"
                         placeholder="归还数量"></el-input-number>
      </el-form-item>

    </el-form>


    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" v-prevent-db-click @click="dataFormSubmit()">借阅</el-button>
    </span>
  </el-dialog>

</template>

<script>
import '@/utils/preventDbClick'

export default {
  data () {
    var filterByName = (query, item) => {
      return item.label.indexOf(query) > -1
    }
    let validateNumber = (rule, value, callback) => {
      console.log(`value is ${value}`)
      if (parseInt(value) === 0) {
        callback(new Error('借阅数量为空'))
      } else {
        callback()
      }
    }

    return {
      visible: false,
      filterByName,
      authorList: [],
      authorMap: {},
      dataForm: {
        id: 0,
        borrowId: 0,
        name: '',
        version: '',
        vendor: '',
        summary: '',
        status: 1,
        publicDate: '',
        total: '',
        available: 0,
        authorIdList: [],
        createTime: '',
        authorNames: '',
        borrowCount: 0,
        limitTime: '',
        needBack: 0,
        returnCount: 0,
        image: [
          'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg', 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg', 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'],
        fit: 'cover'
      },

      dataRule: {
        borrowCount: [
          // { required: true, message: '借阅数量为空', trigger: 'blur' },
          {validator: validateNumber, message: '借阅数量为空', trigger: 'blur'}
        ],
        limitTime: [
          {required: true, message: '还书时间不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    init (id, borrowId, total) {
      this.dataForm.id = id || 0
      this.dataForm.borrowId = borrowId || 0
      this.$http({
        url: this.$http.adornUrl('/sys/author/select'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        this.authorList = data && data.code === 0 ? data.list.map((e) => {
          return {key: e.authorId, label: e.username}
        }) : []
        data.list.forEach((item) => {
          this.authorMap[item['authorId']] = item
        })
        console.log(this.authorList)
      }).then(() => {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
      }).then(() => {
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/sys/book/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.book.name
              this.dataForm.version = data.book.version
              this.dataForm.vendor = data.book.vendor
              this.dataForm.summary = data.book.summary
              this.dataForm.status = data.book.status
              this.dataForm.publicDate = data.book.publicDate
              this.dataForm.total = data.book.total
              this.dataForm.available = data.book.available
              this.dataForm.authorIdList = data.book.authorIdList
              this.dataForm.createTime = data.book.createTime
              this.dataForm.authorNames = data.book.authorIdList.map((e) => {
                return this.authorMap[e]['username']
              }).join(',')
              this.dataForm.needBack = total
            }
          })
        }
      })
    },

    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/sys/return/${!this.dataForm.id ? 'save' : 'update/' + this.dataForm.borrowId}`),
            method: 'post',
            data: this.$http.adornData({
              'total': this.dataForm.returnCount,
              'borrowId': this.dataForm.borrowId || undefined
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
